#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 19-5-26 21:25
# @Author  : JSQ
# @File    : tcpclient.py
# @Software: PyCharm
# socket_server传输文件客户端，发送文件

import os
import json
import struct
from socket import *

#对报头进行打包
def operafile(path, filename):
    filesize_bytes = os.path.getsize(path + filename)
    head_dir = {
        'filename': filename,
        'filesize_bytes': filesize_bytes,
    }
    head_info = json.dumps(head_dir)
    head_info_len = struct.pack('i', len(head_info))
    return head_info_len, head_info

#发送真实文件
def sendRealFile(conn, filepath, filename):
    with open(filepath + filename, 'rb')as f:
        conn.sendall(f.read())
    print('发送成功-->',filename)

def send():
    HOST_S1 = '172.16.0.2'
    HOST_S2 = '172.16.0.3'
    HOST_control = '172.16.0.5'
    tag = 1                                        # 预留触发器，决定何时发送文件
    tcp_client2S1 = socket(AF_INET, SOCK_STREAM)
    tcp_client2S1.connect_ex((HOST_S1, 8080))
    tcp_client2S2 = socket(AF_INET, SOCK_STREAM)
    tcp_client2S2.connect_ex((HOST_S2, 8080))
    tcp_client2c = socket(AF_INET, SOCK_STREAM)
    tcp_client2c.connect_ex((HOST_control, 8080))
    
    print('开始向S1发送转移指令#######################')
    if tag == 1:
        path = os.getcwd() + '/JsonFileCmd/'       # 获取当前工程下的JsonFileCmd目录
        dirs = os.listdir(path)
        for i in dirs:                             # 循环读取路径下的文件
            if os.path.splitext(i)[1] == ".json":
                head_info_len, head_info = operafile(path, i)
                tcp_client2S1.send(head_info_len)
                tcp_client2S1.send(head_info.encode('utf-8'))
                sendRealFile(tcp_client2S1, path, i)
        tcp_client2S1.close()

    print('开始向S2发送转移指令#######################')
    if tag == 1:
        path = os.getcwd() + '/JsonFileCmd/'       # 获取当前工程下的JsonFileCmd目录
        dirs = os.listdir(path)
        for i in dirs:                             # 循环读取路径下的文件
            if os.path.splitext(i)[1] == ".json":
                head_info_len, head_info = operafile(path, i)
                tcp_client2S2.send(head_info_len)
                tcp_client2S2.send(head_info.encode('utf-8'))
                sendRealFile(tcp_client2S2, path, i)

    print('开始向control发送转移指令##################')
    if tag == 1:
        path = os.getcwd() + '/JsonFileCmd/'       # 获取当前工程下的JsonFileCmd目录
        dirs = os.listdir(path)
        for i in dirs:                             # 循环读取路径下的文件
            if os.path.splitext(i)[1] == ".json":
                head_info_len, head_info = operafile(path, i)
                tcp_client2c.send(head_info_len)
                tcp_client2c.send(head_info.encode('utf-8'))
                sendRealFile(tcp_client2c, path, i)

if __name__ == '__main__':
    send()